/**
* Project: yui3-common-mybatisx
 * Class TableUtils
 * Version 1.0
 * File Created at 2019年1月21日
 * $Id$
 * author yuyi
 * email 1060771195@qq.com
 */
package yui.comn.mybatisx.core.toolkit;

import java.lang.reflect.Field;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableName;
import com.baomidou.mybatisplus.core.config.GlobalConfig;
import com.baomidou.mybatisplus.core.metadata.TableInfo;
import com.baomidou.mybatisplus.core.metadata.TableInfoHelper;
import com.baomidou.mybatisplus.core.toolkit.ClassUtils;
import com.baomidou.mybatisplus.core.toolkit.GlobalConfigUtils;
import com.baomidou.mybatisplus.core.toolkit.StringPool;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;

import yui.comn.mybatisx.annotation.TenantId;

/**
 * 表工具类
 * @author yuyi (1060771195@qq.com)
 */
public class TableUtils {

    /**
     * 储存反射类表信息
     */
    private static final Map<Class<?>, String> TABLE_NAME_CACHE = new ConcurrentHashMap<>();
    
    /**
     * 获取租户ID, key表名
     */
    private static final Map<Class<?>, String> TENANT_ID_CACHE = new ConcurrentHashMap<>();
    
    
    public static final String getTenantId(Class<?> entityClass) {
        String info = TENANT_ID_CACHE.get(entityClass);
        if (null == info) {
            List<Field> fieldList = TableInfoHelper.getAllFields(ClassUtils.getUserClass(entityClass));
            for (Field field : fieldList) {
                TenantId annotation = field.getAnnotation(TenantId.class);
                if (null != annotation) {
                    info = getTableFieldName(field, entityClass);
                    TENANT_ID_CACHE.put(entityClass, info);
                }
            }
        }
        return info;
    }
    
    private static String getTableFieldName(Field field, Class<?> entityClass) {
        TableField tf = field.getAnnotation(TableField.class);
        if (null != tf && StringUtils.isNotBlank(tf.value())) {
            return tf.value();
        }
        
        GlobalConfig globalConfig = GlobalConfigUtils.defaults();
        GlobalConfig.DbConfig dbConfig = globalConfig.getDbConfig();
        TableInfo tableInfo = TableInfoHelper.getTableInfo(entityClass);
        
        String column = field.getName();
        if (tableInfo.isUnderCamel()) {
            /* 开启字段下划线申明 */
            column = StringUtils.camelToUnderline(column);
        }
        if (dbConfig.isCapitalMode()) {
            /* 开启字段全大写申明 */
            column = column.toUpperCase();
        }
        return column;
    }
    
    public static String getEntityName(Class<?> entityClass) {
        String entityName = entityClass.getSimpleName();
        return StringUtils.firstToLowerCase(entityName);
    }
    
    public static String getTableName(Class<?> clazz) {
        String tableName = TABLE_NAME_CACHE.get(clazz);
        if (StringUtils.isBlank(tableName)) {
            /* 设置表名 */
            TableName table = clazz.getAnnotation(TableName.class);
            tableName = clazz.getSimpleName();
            if (table != null && StringUtils.isNotBlank(table.value())) {
                tableName = table.value();
            } else {
                // 开启表名下划线申明
                tableName = StringUtils.camelToUnderline(tableName);
                tableName = tableName.replace("_vo", "");
                // 首字母小写
                tableName = StringUtils.firstToLowerCase(tableName);
                // 存在表名前缀
                tableName = "t_" + tableName;
            }
            TABLE_NAME_CACHE.put(clazz, tableName);
        }
        return tableName;
    }
    
    public static String sqlSelect(Class<?> entityClass, String... columns) {
        // TableInfo tableInfo = TableInfoHelper.getTableInfo(entityClass); 兼容web端不能获取表名，统一获取表名
        String tableName = null;
        if (null != entityClass) {
            tableName = getTableName(entityClass);
        }
        return sqlSelect(tableName, columns);
    }
    
    public static String sqlSelect(String tableName, String... columns) {
        StringBuffer colBuff = new StringBuffer();
        for (String column : columns) {
            if (colBuff.length() > 0) {
                colBuff.append(StringPool.COMMA).append(StringPool.SPACE);
            }
            if (column.contains(StringPool.LEFT_BRACKET) || column.contains(StringPool.SPACE) || column.contains(" as ")) {
                // 主要对 count(t_sys_user.id) as count 处理类似情况
                colBuff.append(column);
            } else if (!column.contains(StringPool.DOT)) {
                if (StringUtils.isNotBlank(tableName)) {
                    colBuff.append(tableName).append(StringPool.DOT)
                    .append(StringPool.BACKTICK).append(column).append(StringPool.BACKTICK);
                    
                    colBuff.append(StringPool.SPACE).append(tableName)
                    .append(StringPool.UNDERSCORE).append(StringPool.UNDERSCORE)
                    .append(column);
                } else {
                    colBuff.append(column);
                }
            } else {
                // String[] cols = StringUtils.split(column, StringPool.DOT);
                // String[] cols = column.split(StringPool.DOT);
                String[] cols = org.springframework.util.StringUtils.split(column, StringPool.DOT);
                if (!column.contains(StringPool.BACKTICK)) {
                    colBuff.append(cols[0]).append(StringPool.DOT)
                    .append(StringPool.BACKTICK).append(cols[1]).append(StringPool.BACKTICK);
                    
                    colBuff.append(StringPool.SPACE).append(cols[0])
                    .append(StringPool.UNDERSCORE).append(StringPool.UNDERSCORE)
                    .append(cols[1]);
                } else {
                    colBuff.append(column);
                    
                    colBuff.append(StringPool.SPACE).append(cols[0])
                    .append(StringPool.UNDERSCORE).append(StringPool.UNDERSCORE)
                    .append(cols[1].replaceAll(StringPool.BACKTICK, ""));
                }
            }
        }
        
        return colBuff.toString();
    }
    
    public static void main(String[] args) {
        String column = "t_sys_user.username";
        String[] cols = org.springframework.util.StringUtils.split(column, ".");
        // String[] cols = column.split(".");
        System.out.println(cols);
    }
}
